import React, { useState, useEffect } from 'react';
import { Modal, Upload, message, Button, Icon } from 'antd';
import PropTypes from 'prop-types';
import cn from 'classnames';
import _ from 'lodash';
import { batchAddAssets, downloadImportFailedSitesForm } from '@api/asset';

import './index.less';

const BatchImportModal = props => {
  const { visible = false, onClose, afterSuccess } = props;

  const [isExporting, setIsExporting] = useState(false);
  const [failedFilename, setFailedFilename] = useState('');
  const [fileList, setFileList] = useState([]);
  const [exceedMax, setExceedMax] = useState(false);

  useEffect(() => {
    setIsExporting(false);
    setExceedMax(false);
    setFailedFilename('');
    setFileList([]);
  }, [visible]);

  const onOk = () => {
    if (!fileList || !fileList[0]) {
      return;
    }
    setIsExporting(true);
    const body = new FormData();
    body.append('file', fileList[0]);
    batchAddAssets(body)
      .then(res => {
        const { fail, failedFilename } = _.get(res, 'data.data', {});
        if (fail && failedFilename) {
          setFailedFilename(failedFilename);
          afterSuccess(false);
        } else {
          message.success('批量导入资产成功');
          afterSuccess();
        }
      })
      .catch(res => {
        const msg = _.get(res, 'message', {});
        message.error(msg || '批量导入资产失败');
        afterSuccess(false);
        if (msg.includes('可添加资产数已达上限')) {
          setExceedMax(true);
        }
      })
      .finally(() => {
        setIsExporting(false);
      });
  };

  const beforeUpload = file => {
    setFileList([file]);
    return false;
  };

  const onRemove = () => {
    setFileList([]);
  };

  const downloadFailed = () => {
    if (failedFilename) {
      downloadImportFailedSitesForm(failedFilename);
    }
  };

  const renderFailTip = failMsg => {
    const exceedLimit = (
      <div className={cn('content', 'first-wrapper', 'exceed-max')}>
        添加资产失败！可管理资产数已达上限。
      </div>
    );
    const vailFail = (
      <div>
        <div className={cn('content', 'first-wrapper')}>
          部分资产导入失败，请您核验填写的IP、URL、权重等格式是否正确
        </div>
        <div className="content">
          <a onClick={downloadFailed}>下载添加失败的资产名单</a>
        </div>
      </div>
    );
    return failMsg ? exceedLimit : vailFail;
  };

  const modalFooter = () => {
    if (failedFilename || exceedMax) {
      return (
        <Button type="primary" onClick={onClose}>
          确定
        </Button>
      );
    }
    return (
      <div>
        <Button onClick={onClose}>取消</Button>
        <Button loading={isExporting} type="primary" onClick={onOk}>
          确定
        </Button>
      </div>
    );
  };

  return (
    <div className="aml-c-batch-import-modal">
      <Modal
        maskClosable={false}
        className={cn(
          'batch-import-modal',
          'no-header-bottom-lines',
          'bottom-center',
          'padding-24'
        )}
        title="批量导入"
        visible={visible}
        footer={modalFooter()}
        onCancel={onClose}
        confirmLoading={isExporting}
      >
        {!failedFilename.length ? (
          <div>
            <div className={cn('content', 'first-wrapper')}>
              <div className="item">
                <span className="name">地址</span>
                <div>
                  <Upload
                    accept=".xlsx"
                    fileList={fileList}
                    beforeUpload={beforeUpload}
                    onRemove={onRemove}
                  >
                    <Button>
                      <Icon type="upload" /> 点击上传&quot;.xlsx&quot;格式文件
                    </Button>
                  </Upload>
                </div>
              </div>
            </div>
            <div className="content">
              <div className="item">
                <span className="name">文件</span>
                <a className="download-example" href="/example.xlsx">
                  下载模板
                </a>
              </div>
            </div>
          </div>
        ) : (
          <div>{renderFailTip(exceedMax)}</div>
        )}
      </Modal>
    </div>
  );
};

BatchImportModal.propTypes = {
  visible: PropTypes.bool,
  onClose: PropTypes.func,
  afterSuccess: PropTypes.func,
  organizationTree: PropTypes.array,
  onOrgPopupVisibleChange: PropTypes.func
};

export default BatchImportModal;
